<template>
  <div class="container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>旷寝学生登记表</span>
          <div class="header-actions">
            <el-button type="primary" @click="goToAdd">新增</el-button>
            <el-date-picker v-model="searchDate" type="date" placeholder="选择日期"
              style="width: 150px; margin-right: 10px;" value-format=" " @change="fetchAbsences" />
            <el-input v-model="searchDormBuild" placeholder="宿舍楼名称" style="width: 150px; margin-right: 10px;" clearable
              @clear="fetchAbsences" @keyup.enter="fetchAbsences" />
            <el-input v-model="searchStudent" placeholder="学生姓名/学号" style="width: 180px; margin-right: 10px;" clearable
              @clear="fetchAbsences" @keyup.enter="fetchAbsences" />
          </div>
        </div>
      </template>

      <el-table :data="absences" border style="width: 100%" v-loading="loading">
        <el-table-column prop="studentName" label="姓名" width="120" sortable />
        <el-table-column prop="dormBuildName" label="宿舍楼" width="120" sortable />
        <el-table-column prop="dormName" label="宿舍号" width="100" sortable />
        <el-table-column prop="absenceDate" label="旷寝日期" width="120" sortable>
          <template #default="{ row }">
            {{ formatDate(row.absenceDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="原因" min-width="200" />
        <el-table-column prop="createTime" label="登记时间" width="160" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-tooltip content="删除" placement="top">
                <el-button size="small" @click="deleteAbsence(scope.row)" type="danger">
                  <el-icon>
                    <DeleteFilled />
                  </el-icon>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" @size-change="fetchAbsences"
          @current-change="fetchAbsences" />
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
import { DeleteFilled } from '@element-plus/icons-vue'

export default {
  components: {
    DeleteFilled
  },
  data() {
    return {
      absences: [],
      loading: false,
      searchDate: '',
      searchDormBuild: '',
      searchStudent: '',
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  created() {
    this.fetchAbsences();
  },
  methods: {
    goToAdd() {
      this.$router.push('/addAbsence');
    },

    async fetchAbsences() {
      this.loading = true;
      try {
        let params = {
          page: this.currentPage,
          size: this.pageSize
        };

        if (this.searchDate) params.date = this.searchDate;
        if (this.searchDormBuild) params.dormBuildName = this.searchDormBuild;
        if (this.searchStudent) {
          if (/^\\d+$/.test(this.searchStudent)) {
            params.studentId = this.searchStudent;
          } else {
            params.studentName = this.searchStudent;
          }
        }

        const response = await axios.get("http://localhost:8080/UserMgr_Web_exploded/absences", {
          params,
          headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
          }
        });

        this.absences = response.data.list || response.data;
        this.total = response.data.total || response.data.length;
      } catch (error) {
        ElMessage.error('获取旷寝记录失败');
        console.error(error);
      } finally {
        this.loading = false;
      }
    },

    async deleteAbsence(absence) {
      try {
        await ElMessageBox.confirm('确定要删除此旷寝记录吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        await axios.delete(
          `http://localhost:8080/UserMgr_Web_exploded/absences/${absence.absenceId}`,
          {
            headers: {
              'Authorization': 'Bearer ' + localStorage.getItem('token')
            }
          }
        );

        ElMessage.success('删除成功');
        this.fetchAbsences();
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败');
          console.error(error);
        }
      }
    },

    formatDate(date) {
      if (!date) return '';
      if (typeof date === 'string') return date;
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
    },

    formatDateTime(datetime) {
      if (!datetime) return '';
      const d = new Date(datetime);
      return `${this.formatDate(d)} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-button-group {
  display: flex;
  gap: 5px;
}
</style>